#!/usr/bin/env zsh

function __zgenom_bin() {
    local file="${1}"
    local name="${2:-${file:t}}"
    local destination="$ZGENOM_SOURCE_BIN/$name"
    if [[ ! -e $destination ]] ln -s $file $destination
}

function __zgenom_bins() {
    setopt localoptions nullglob
    for file in $~1(*); do
        __zgenom_bin "$file"
    done
}

function zgenom-bin() {
    local location branch name glob
    zparseopts -D -E -location:=location -branch:=branch -name:=name -glob:=glob || return

    local dir
    if [[ "$#" == 0 ]]; then
        __zgenom_err '`bin` requires at least one parameter:'
        __zgenom_err '`zgenom bin <repo>`'
        __zgenom_err '--location, --branch, --name, --glob'
        return
    elif [[ "${1[1]}" == '/' || "${1[1]}" == '.'  ]]; then
        dir="$1"
    else
        local repo="$1"
        branch="${branch[2]:-$3}"
        dir="$(__zgenom_clone_dir $repo --branch $branch)"

        zgenom-clone "$repo" "$branch"
    fi

    location="${${location[2]:-$2}%/}"
    name="${name[2]:-$4}"

    if [[ ! -d $ZGENOM_SOURCE_BIN ]] mkdir -p $ZGENOM_SOURCE_BIN

    if [[ -n $glob ]] __zgenom_bins "$dir/${glob[2]}"

    if [[ -n $location ]]; then
        location="$dir/$location"
        if [[ -f "$location" ]]; then
            __zgenom_bin "$location" $name
            return
        fi
    elif [[ -n $glob ]]; then
        # Stop is glob is used and no location is provided
        return
    elif [[ -d "$dir/bin" ]]; then
        location="$dir/bin"
    else
        location="$dir"
    fi

    __zgenom_bins "$location/*"
}

zgenom-bin $@
